<template>
  <component
    :is="componentName"
    v-model="value"
    :startPlaceholder="startPlaceholder"
    :endPlaceholder="endPlaceholder"
    :type="pickerType"
    :format="format"
    clearable
    style="width: 100%"
  />
</template>

<script setup>
import { inject, computed, watch } from "vue";
import { get, set, isArray } from "lodash";

const props = defineProps({
  component: Object,
});

const emit = defineEmits(["update:modelValue"]);
const searchForm = inject("searchForm");

// 解析基本属性
const formType = props.component.formType || "date";
const isRange = props.component.range === true;

// 动态组件名（Element Plus）
const componentName = computed(() => {
  return  "el-date-picker";
});

// 动态 type 类型
const pickerType = computed(() => {
  return "daterange";
  if (isRange) {
    return "daterange";
    if (formType === "time") return "timerange";
    if (formType === "datetime") return "datetimerange";
    return "daterange";
  }
  return formType;
});

// 默认格式 & 绑定值格式
const format = computed(() => props.component.format || "YYYY-MM-DD HH:mm:ss");
const valueFormat = computed(
  () => props.component.valueFormat || "YYYY-MM-DD HH:mm:ss"
);

// 占位符
const startPlaceholder = computed(() => {
  return isRange ? "开始时间" : `请选择${props.component.title ?? ""}`;
});
const endPlaceholder = computed(() => (isRange ? "结束时间" : ""));

// 默认时间（只对日期 range 有意义）
const defaultTime = computed(() => {
  if (isRange && formType === "date") {
    return ["00:00:00", "23:59:59"];
  }
  return isRange && formType !== "time" ? ["00:00:00", "23:59:59"] : undefined;
});

// v-model 绑定
const value = computed({
  get() {
    let val = get(searchForm.value, props.component.dataIndex);
    if (val === undefined || val === null) {
      val = isRange
        ? props.component.searchDefaultValue ?? []
        : props.component.searchDefaultValue ?? "";
    } else if (isRange && !isArray(val)) {
      console.warn(
        `Range field ${props.component.dataIndex} is not an array:`,
        val
      );
      val = [val];
    }
    return val;
  },
  set(newVal) {
    if (newVal === undefined || newVal === null) {
      newVal = isRange ? [] : "";
    } else if (isRange && !isArray(newVal)) {
      console.warn(
        `Setting range field ${props.component.dataIndex} to non-array:`,
        newVal
      );
      newVal = [newVal];
    }
    emit("update:modelValue", newVal);
    set(searchForm.value, props.component.dataIndex, newVal);
  },
});

// 调试：监控 searchForm 值变化
watch(
  () => searchForm.value[props.component.dataIndex],
  (newVal) => {
    console.log(
      `searchForm[${props.component.dataIndex}] updated to:`,
      newVal
    );
  },
  { deep: true }
);
</script>